package cn.wbnull.springbootdemo.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Scope;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**
 * 功能描述
 *
 * @author EDZ
 * @since 2022-08-01
 */
@RestController
@RequestMapping("/file")
public class FileController {
    @PostMapping(value = "/fileUpload")
    public String fileUpload(@RequestParam(value = "file") MultipartFile file, Model model, HttpServletRequest request) {
        if (file.isEmpty()) {
            System.out.println("文件为空空");
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = "D://temp-rainy//"; // 上传后的路径
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String filename = "/temp-rainy/" + fileName;
//        model.addAttribute("filename", filename);
        return filePath;
    }

    @RequestMapping ( "fileUpload2" )
    public  String  fileUpload2( @RequestParam (value = "file" ) MultipartFile file)  throws  IOException {
        long   startTime=System.currentTimeMillis();
        System.out.println( "fileName：" +file.getOriginalFilename());
        String path= "E:/" + new Date().getTime()+file.getOriginalFilename();

        File newFile= new  File(path);
        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        file.transferTo(newFile);
        long   endTime=System.currentTimeMillis();
        System.out.println( "采用file.Transto的运行时间：" +String.valueOf(endTime-startTime)+ "ms" );
        return  "/success" ;
    }

}
